<?php

namespace app\admin\service\common;

use app\admin\model\auth\AdminModel;
use app\admin\model\common\ConfigCateModel;
use app\admin\model\common\ConfigModel;
use think\facade\Db;
use app\admin\service\BaseService;

class ConfigService extends BaseService
{

    /**
     * 获取列表
     * @param $data
     * @return mixed
     */
    public function getList($param)
    {
        $model = new ConfigCateModel();
        $searchFields = ['name'];//模糊搜索
        $search = ['status'];//精准搜索
        $fields = [];//查询字段
        $list = $this->paginateWithSearch($model, $param, $fields, $searchFields, $search ,'created_at','asc');
        return success($list);
    }
    public function addCate($data)
    {
        $model = new ConfigCateModel();
        $Unique = ['name'];
        $empty = ['name'];
        $check = $this->checkParams($model, $data, $Unique, $empty);
        if ($check !== true) {
            return fail($check['msg']);
        }
      
        $data['created_at'] = time();
        Db::startTrans();
            try{
                $model->insertGetId($data);
                Db::commit();
                $this->writeLog('添加', 1);
                return success();
            } catch (\Exception $e) {
                Db::rollback();
                return fail('操作失败:' . $e->getMessage());
        }
    }
    public function editCate($id, $data)
    {
        $model = new ConfigCateModel();
        $res = $model->where('id', $id)->find();
        if (empty($res)) {
            return fail('用户不存在');
        }
        $Unique = ['name'];
        $empty = ['name'];
        $data['id'] = $id;
        $check = $this->checkParams($model, $data, $Unique, $empty);
        if ($check !== true) {
            return fail($check['msg']);
        }
        
        Db::startTrans();
        unset($data['id']);
            try{
                $data['updated_at'] = time();
                $model->where('id', $id)->update($data);
                Db::commit();
                $this->writeLog('编辑', 2);
                return success();
            } catch (\Exception $e) {
                Db::rollback();
                return fail('操作失败:' . $e->getMessage());
        }
    }
    public function deleteCate($ids)
    {
      $model = new ConfigCateModel();
      $configModel = new ConfigModel();
      $ids = array_filter(array_unique($ids));
      if (empty($ids)) {
          return fail('请选择要删除的数据');
      }
      foreach ($ids as $id) {
          if (!is_numeric($id) || $id <= 0) {
              return fail('包含错误ID值'.$id);
          }
        $count = $configModel->where('block', $id)->count();
        if ($count > 0) {
            return fail('分类ID '.$id.' 下存在配置数据，无法删除');
        }
      }
      $ids = array_map('intval', $ids);
      Db::startTrans();
        try{
            $model->whereIn('id', $ids)->delete();
            Db::commit();
            $this->writeLog('删除'. implode(',', $ids), 3);
            return success();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('操作失败:' . $e->getMessage());
        }
    }
    public function getConfig($param)
    {
        $model = new ConfigModel();
        $query = $model->where('status', 1);
        if (isset($param['block']) && $param['block'] !== '') {
            $query->where('block', $param['block']);
        }
        if (!empty($param['search'])) {
            $kw = trim($param['search']);
            $query->where(function ($q) use ($kw) {
                $q->where('value', 'like', "%{$kw}%")
                  ->whereOr('name', 'like', "%{$kw}%")
                  ->whereOr('`key`', 'like', "%{$kw}%");
            });
        }
        $list = $query->select()->toArray();
        return success($list);
    }
    public function save($param)
    {
        $model = new ConfigModel();
        if (isset($param[0]) && is_array($param[0])) {
            if (empty($param)) {
                return fail('没有需要保存的数据');
            }
            $hasUpdate = false;
            foreach ($param as $item) {
                if (!isset($item['id'])) continue;
                $model->where('id', $item['id'])->update(['value' => $item['value']]);
                $hasUpdate = true;
            }
            if (!$hasUpdate) {
                return fail('没有需要保存的数据');
            }
            return success([],'编辑成功');
        } else {
            if (empty($param['id'])) {
                return fail('没有需要保存的数据');
            }
            if (!isset($param['value'])) {
                return fail('没有需要保存的数据');
            }
            $model->where('id', $param['id'])->update(['value' => $param['value']]);
            return success([],'编辑成功');
        }
    }
    public function Add($data)
    {
        $model = new ConfigModel();
        $Unique = ['name','key','value'];
        $empty = ['name','value','key'];
        $check = $this->checkParams($model, $data, $Unique, $empty);
        if ($check !== true) {
            return fail($check['msg']);
        }
        Db::startTrans();
            try{
                $model->insertGetId($data);
               
                Db::commit();
                $this->writeLog('添加', 1);
                return success();
            } catch (\Exception $e) {
                Db::rollback();
                return fail('操作失败:' . $e->getMessage());
        }
    }
    public function Delete($ids)
    {
        $model = new ConfigModel();
        $ids = array_filter(array_unique($ids));
        if (empty($ids)) {
            return fail('请选择要删除的数据');
        }
        foreach ($ids as $id) {
            if (!is_numeric($id) || $id <= 0) {
                return fail('包含错误ID值'.$id);
            }
        }
        $ids = array_map('intval', $ids);
        Db::startTrans();
            try{
                $model->whereIn('id', $ids)->delete();
                Db::commit();
                $this->writeLog('删除'. implode(',', $ids), 3);
                return success();
            } catch (\Exception $e) {
                Db::rollback();
                return fail('操作失败:' . $e->getMessage());
        }
    }
}
